#include <iostream>
#include <string>
#include <unistd.h>
#include <pthread.h>

using namespace std;

//创建一把全局的锁并初始化
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
void* active(void* args)
{
    string name = static_cast<const char*>(args);
    while(true)
    {
        pthread_mutex_lock(&mutex);
        pthread_cond_wait(&cond,&mutex);//在指定的条件变量在等待，但是线程申请的锁还没有释放
        //向显示器上打印，显示器文件也是公共资源
        printf("%s is active !\n",name.c_str());
        pthread_mutex_unlock(&mutex);
    }
}

int main()
{
    pthread_t tid1,tid2,tid3;
    pthread_create(&tid1,nullptr,active,(void*)"thread-1");
    pthread_create(&tid1,nullptr,active,(void*)"thread-2");
    pthread_create(&tid1,nullptr,active,(void*)"thread-3");
    
    sleep(1);
    printf("main thread ctrl begin...\n");
    while(true)
    {
        printf("main wakeup thread...\n");
        //唤醒线程---唤醒在指定条件变量在等待的线程
        //pthread_cond_signal(&cond);
        pthread_cond_broadcast(&cond);
        sleep(1);
    }

    pthread_join(tid1,nullptr);
    pthread_join(tid2,nullptr);
    pthread_join(tid3,nullptr);
    return 0;
}